package com.mall.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.common.enums.UserStatusEnum;
import com.mall.common.exception.BizException;
import com.mall.common.enums.ResponseEnum;
import com.mall.user.entity.param.UserAddParam;
import com.mall.user.entity.param.UserEditParam;
import com.mall.user.entity.po.Role;
import com.mall.user.entity.po.User;
import com.mall.user.entity.po.UserRole;
import com.mall.user.entity.vo.RoleVO;
import com.mall.user.entity.vo.UserVO;
import com.mall.user.entity.vo.UserWithRoleInfoVO;
import com.mall.user.enums.RedisKeyPrefixEnum;
import com.mall.user.mapper.RoleMapper;
import com.mall.user.mapper.UserMapper;
import com.mall.user.mapper.UserRoleMapper;
import com.mall.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starters.redisson.config.RedissonDistributedLocker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wuyijie
 * @since 2021-06-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private UserMapper userMapper;
    private UserRoleMapper userRoleMapper;
    private RoleMapper roleMapper;
    private RedissonDistributedLocker redissonDistributedLocker;
    private PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, UserRoleMapper userRoleMapper,
                           RoleMapper roleMapper, RedissonDistributedLocker redissonDistributedLocker,
                           PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.userRoleMapper = userRoleMapper;
        this.roleMapper = roleMapper;
        this.redissonDistributedLocker = redissonDistributedLocker;
        this.passwordEncoder=passwordEncoder;
    }

    @Override
    public int add(UserAddParam userAddParam) {
        int add;
        String lockerKey = RedisKeyPrefixEnum.LOCKER_USER_NAME.getPerfix() + userAddParam.getUsername();
        try {
            redissonDistributedLocker.tryLock(lockerKey);
            UserVO userVO = this.queryByUsername(userAddParam.getUsername());

            if (ObjectUtil.isNull(userVO)) {
                User user = BeanUtil.toBean(userAddParam, User.class);
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                user.setStatus(1);
                add = userMapper.insert(user);
                return add;
            } else {
                throw new BizException(ResponseEnum.OBJECT_ALREAD_EXIST_ERROE);
            }
        } catch (Exception e) {
            throw new BizException(ResponseEnum.INTERNAL_SERVER_ERROR, e);
        } finally {
            redissonDistributedLocker.unLock(lockerKey);
        }
    }

    @Override
    public int deleteById(int id) {
        int delete;
        delete = userMapper.deleteById(id);
        return delete;
    }

    @Override
    public int edit(UserEditParam userEditParam) {
        UserVO edit = null;
        User user = BeanUtil.toBean(userEditParam, User.class);
        userMapper.updateById(user);
        edit = BeanUtil.toBean(user, UserVO.class);

        return 1;
    }

    @Override
    public UserVO queryById(int id) {
        UserVO userVO = null;
        User user = userMapper.selectById(id);
        userVO = BeanUtil.toBean(user, UserVO.class);
        return userVO;
    }

    @Override
    public UserVO queryByUsername(String username) {
        UserVO userVO = null;
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        userVO = BeanUtil.toBean(user, UserVO.class);
        return userVO;
    }

    @Override
    public UserWithRoleInfoVO queryUserWithRoleVOByUsername(String username) {
        UserWithRoleInfoVO result;
        User user = userMapper.queryUserWithRoleByUsername(username, UserStatusEnum.USING.getCode());
        result = BeanUtil.toBean(user, UserWithRoleInfoVO.class);
        if (ObjectUtil.isNotNull(user)) {
            LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userRoleLambdaQueryWrapper.eq(UserRole::getUserId, user.getId());
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleLambdaQueryWrapper);
            if (CollUtil.isNotEmpty(userRoles)) {
                LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                roleLambdaQueryWrapper.in(Role::getId, userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
                List<Role> roleList = roleMapper.selectList(roleLambdaQueryWrapper);
                List<RoleVO> roleVOList = result.getRoleList();
                roleList.forEach(role -> {
                    roleVOList.add(BeanUtil.toBean(role, RoleVO.class));
                });
                result.setRoleList(roleVOList);
            }
        }
        return result;
    }

    @Override
    public UserVO queryByUsernameAndPassword(String username, String password) {
        UserVO userVO = null;
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, username);
        userLambdaQueryWrapper.eq(User::getPassword, password);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        userVO = BeanUtil.toBean(user, UserVO.class);
        return userVO;
    }
}
